package com.ph.controller.personal.bankcard;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.ph.constant.PsResultEnum;
import com.ph.custom.annotation.MemberCache;
import com.ph.custom.cenum.UserCacheEnum;
import com.ph.entity.MemberInfo;
import com.ph.shopping.common.core.customenum.MemberEnum;
import com.ph.shopping.common.core.customenum.ResultEnum;
import com.ph.shopping.common.util.result.Result;
import com.ph.shopping.facade.member.dto.BankBindInfoDto;
import com.ph.shopping.facade.member.dto.BankCardBindInfoDto;
import com.ph.shopping.facade.member.entity.BankCodeAndName;
import com.ph.shopping.facade.member.entity.Member;
import com.ph.shopping.facade.member.service.IBankCardBindService;
import com.ph.shopping.facade.member.service.ICretificateAuthService;
import com.ph.shopping.facade.member.service.IMemberService;
import com.ph.util.BankCardUtil;
import com.ph.util.ResultUtil;

/**
 * 
 * @ClassName:  BankCardController   
 * @Description:银行卡相关action 
 * @author: lijie
 * @date:   2017年4月17日 上午10:03:29     
 * @Copyright: 2017
 */
@Controller
@RequestMapping("bankcard")
public class BankCardController {

	private static final Logger logger = LoggerFactory.getLogger(BankCardController.class);
	
	@Reference(version = "1.0.0", retries = 0, timeout = 30000)
	private ICretificateAuthService cretificateAuthService;
	
	@Reference(version = "1.0.0", retries = 0, timeout = 30000)
	private IBankCardBindService bankCardBindService;
	
	@Reference(version = "1.0.0", retries = 0, timeout = 30000)
	private IMemberService memberService;
	/**
	 * 
	 * @Title: loadAccountSecurity   
	 * @Description: 加载银行卡页面   
	 * @param: @param request
	 * @param: @param model
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	@MemberCache
	@RequestMapping(value = "/loadBankCard", method = RequestMethod.GET)
	public String loadAccountSecurity(HttpServletRequest request,HttpServletResponse response,Model model,MemberInfo memberInfo) {
		try {
			if (memberInfo != null) {
				Result result = cretificateAuthService.getCretificateAuthInfo(memberInfo.getIdCard());
				if (result != null && ResultEnum.SUCCESS.getCode().equals(result.getCode())) {
					model.addAttribute("bankInfo", getBankCardInfo(memberInfo.getId()));
					model.addAttribute("cerAuth", result.getData());
					//查询已绑定的银行卡
					return "bankcard/bankcardInfo";
				} 
			}
			response.sendRedirect("/bankcard/loadRealNamePromat");	
		} catch (Exception e) {
			logger.error("加载银行卡页面错误", e);
		}
		return null;
	}
	/**
	 * 
	 * @Title: getBankCardInfo   
	 * @Description: 查询用户绑定的银行卡信息 
	 * @param: @param userId
	 * @param: @return      
	 * @return: BankCardBindInfoDto      
	 * @throws
	 */
	private BankCardBindInfoDto getBankCardInfo(Long userId){
		BankCardBindInfoDto bankCardInfo = null;
		Result result = bankCardBindService.getBankCardInfo(userId, MemberEnum.MEMEBR_BANK.getCode());
		if (result != null && ResultEnum.SUCCESS.getCode().equals(result.getCode())) {
			Object obj = result.getData();
			if(obj instanceof BankCardBindInfoDto){
				bankCardInfo = (BankCardBindInfoDto)obj;
			}
		}
		return bankCardInfo;
	}
	/**
	 * 
	 * @Title: loadRealNamePromat   
	 * @Description: 加载未实名提示页面   
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	@MemberCache
	@RequestMapping(value = "/loadRealNamePromat", method = RequestMethod.GET)
	public String loadRealNamePromat(HttpServletRequest request,Model model){
		
		return "bankcard/realnamePrompt";
	}
	/**
	 * 
	 * @Title: bindBanCard   
	 * @Description:绑定银行卡操作  
	 * @param: @param request
	 * @param: @param dto
	 * @param: @return      
	 * @return: Map<String,Object>      
	 * @throws
	 */
	@RequestMapping("/bindBanCard")
	@ResponseBody
	@MemberCache(userCache = { UserCacheEnum.UPDATE, UserCacheEnum.SELECT })
	public Map<String, Object> bindBanCard(HttpServletRequest request, MemberInfo memberInfo, BankBindInfoDto dto) {
		logger.info("绑定银行卡处理参数：BankBindInfoDto = {} ", JSON.toJSONString(dto));
		Map<String, Object> map = ResultUtil.setResult(false, "绑定失败，请仔细核对你的信息");
		try {
			if (dto != null) {
				if (memberInfo == null || memberInfo.getId() == null) {
					logger.warn("绑定银行卡未获取相关用户信息");
				} else {
					dto.setAccountId(memberInfo.getId());
					dto.setCreateUser(memberInfo.getId().toString());
					dto.setIdCard(memberInfo.getIdCard());
					dto.setUserType(MemberEnum.MEMEBR_BANK.getCode());
					Result result = bankCardBindService.bindBankCardInfo(dto);
					logger.info("绑定银行卡返回数据：Result = {} ", JSON.toJSONString(result));
					if (result != null) {
						String code = result.getCode();
						if (ResultEnum.SUCCESS.getCode().equals(code)) {
							ResultUtil.setResult(map, true, "绑定银行卡成功");
							MemberInfo newmember = getMemberInfoByMobile(memberInfo.getMemberPhone());
							if (newmember != null) {
								BeanUtils.copyProperties(newmember, memberInfo);
							}
						} else if (ResultEnum.MEMBER_DATA_EXISTS.getCode().equals(code)) {
							map.put("message", "当前银行卡已绑定");
						}
					}
				}
			}
		} catch (Exception e) {
			logger.error("绑定银行卡处理错误", e);
			ResultUtil.setResult(map, false, "服务器繁忙请稍后再试");
		}
		return map;
	}
	/**
	 * 
	 * @Title: getBanCardName   
	 * @Description: 根据银行卡考好获取 名称  
	 * @param: @param request
	 * @param: @param bankCardNum
	 * @param: @return      
	 * @return: Map<String,Object>      
	 * @throws
	 */
	@RequestMapping("/getBanCardName")
	@ResponseBody
	public Map<String, Object> getBanCardName(HttpServletRequest request,String bankCardNum) {
		logger.info("根据银行卡卡号获取银行卡名称参数 bankCardNum：" + bankCardNum);
		Map<String, Object> map = ResultUtil.setResult(false, PsResultEnum.FAIL.getMsg());
		try {
			if (StringUtils.isNotBlank(bankCardNum)) {
				if(BankCardUtil.isNoexists(bankCardNum)){
					return map;
				}
				String cardName = BankCardUtil.getBankName(bankCardNum);
				if(StringUtils.isNotBlank(cardName)){
					map.put("cardName", cardName);
					ResultUtil.setResult(map, true, "");
					return map;
				}
				Result result = bankCardBindService.getBankCodeAndNameByCode(bankCardNum);
				logger.info("根据银行卡卡号获取银行卡名称返回数据：Result = {} ", JSON.toJSONString(result));
				boolean flag = false;
				if (result != null) {
					String code = result.getCode();
					if (ResultEnum.SUCCESS.getCode().equals(code)) {
						Object obj = result.getData();
						if((flag = obj instanceof BankCodeAndName)){
							BankCodeAndName bank = (BankCodeAndName)obj;
							map.put("cardName",bank.getBankName());
							BankCardUtil.setCardName(bankCardNum, bank.getBankName());
							ResultUtil.setResult(map, true, "");
						}
					}
				}
				if(!flag){
					BankCardUtil.putNoexists(bankCardNum);
				}
			}
		} catch (Exception e) {
			logger.error("根据银行卡卡号获取银行卡名称错误", e);
			ResultUtil.setResult(map, false, "服务器繁忙请稍后再试");
		}
		return map;
	}
	/**
	 * 
	 * @Title: getMemberInfoByMobile   
	 * @Description: 根据手机号获取会员信息   
	 * @param: @param phone
	 * @param: @return      
	 * @return: MemberInfo      
	 * @throws
	 */
	private MemberInfo getMemberInfoByMobile(String phone){
		MemberInfo memberInfo = null;
		if(StringUtils.isNotBlank(phone)){
			Result result = memberService.getMemberInfoByMobile(phone);
			logger.info("根据手机号获取会员信息返回数据：Result = {} ", JSON.toJSONString(result));
			if (result != null) {
				if (ResultEnum.SUCCESS.getCode().equals(result.getCode())) {
					Object data = result.getData();
					if(data instanceof Member){
						memberInfo = new MemberInfo();
						BeanUtils.copyProperties(data, memberInfo);
					}
				}
			}
		}
		return memberInfo;
	}
}
